import { _decorator, Button, Component, director, find, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

import { levelConfig } from "../Config/Config";
import { GameData } from "../Data/GameData";
import CommonFunction from "../utils/CommonFunction";

@ccclass('MainPanel')
export default class MainPanel extends Component {
    public static Instance: MainPanel;
    @property(Node)
    public Levels: Node | null = null;

    @property(Button)
    Button_close: Button | null = null;
    @property(Button)
    Button_clearData: Button | null = null;

    onLoad() {
        MainPanel.Instance = this;
    }

    ShowOn() {
        this.node.active = true;
        this.AddListener();
        this.Refresh();
    }

    ShowOff() {
        this.node.active = false;
        this.RemoveListener();
    }

    async Refresh() {
        CommonFunction.SetAllChildrenAtive(this.Levels, false);

        let allLevelData = GameData.Get_AllLevelData();
        let count = levelConfig.length; //allLevelData.length
        for (let index = 0; index < count; index++) {
            const child = CommonFunction.GetFreeChild(this.Levels);
            child.active = true;
            let label_level: Label = find(`bg/level`, child).getComponent(Label);
            label_level.string = `${index + 1}`;
            child.on(`click`, () => {
                this.click(index);
            }, this);
        }

        //        // this.click(0);
    }

    click(index) {
        MainPanel.Instance.ShowOff();
        GameData.CurrentLevel = index;
        director.loadScene("GameScene");
    }

    AddListener() {
        this.Button_close.node.on("click", this.On_Button_close, this);
        this.Button_clearData.node.on("click", this.On_Button_clearData, this);

    }

    RemoveListener() {
        this.Button_close.node.off("click", this.On_Button_close, this);
        this.Button_clearData.node.off("click", this.On_Button_clearData, this);
    }

    async On_Button_close() {
        this.ShowOff();
    }

    async On_Button_clearData() {
        localStorage.clear();

        this.ShowOff();
    }
}